#include "InputBox.h"

bool CInputBox::onkeydown(char ch)
{
    switch (ch)
    {
    case '\t':return false; break;
    case '\n':
        if (!Editable)return false;
        //this->_bufText.insert(this->_bufText.begin() + this->_BufPos.Y + 1, this->_bufText[this->_BufPos.Y].substr(this->_BufPos.X));
        //this->_bufText[this->_BufPos.Y].erase(this->_bufText[this->_BufPos.Y].begin() + this->_BufPos.X, this->_bufText[this->_BufPos.Y].end());
        //this->_BufPos.Y++;
        //this->_BufPos.X = 0;

        //this->UpdateData(false);
        //this->submit();

        this->uiupd();
        break;
    case '\b':
        if (!Editable)return false;
        if (_BufPos.X > 0)
        {
            this->_BufPos.X--;
            this->_bufText[this->_BufPos.Y].erase(this->_BufPos.X);
            this->uiupd();
        }
        else
        {
            if (_BufPos.Y > 0)
            {
                this->_BufPos.Y--;
                this->_BufPos.X = this->_bufText[this->_BufPos.Y].size();
                this->_bufText[this->_BufPos.Y].append(this->_bufText[this->_BufPos.Y + 1]);
                this->_bufText.erase(this->_bufText.begin() + this->_BufPos.Y + 1);
                this->uiupd();
            }
        }
    default:
        if (!Editable)return false;
        if (isspace(ch) || isgraph(ch))
        {
            this->_bufText[this->_BufPos.Y].insert(this->_bufText[this->_BufPos.Y].begin() + this->_BufPos.X + 1, ch);

            this->_BufPos.X++;
            if (this->_CurPos.X < this->_size.X - 1)
            {
                this->_CurPos.X++;
            }
            this->uiupd();
            break;
        }
        return false;
    }
    return true;
}

void CInputBox::uiupd()
{
    Coord ViewPos = this->_BufPos - this->_CurPos;
    for (unsigned short y = 0; y < this->_size.Y; y++)
    {
        for (unsigned short x = 0; x < this->_size.X; x++)
        {
            if (ViewPos.Y + y < this->_bufText.size() && ViewPos.X + x < this->_bufText[ViewPos.Y + y].size())
            {
                this->_UIBuf->at({ x, y }) = { this->_bufText[ViewPos.X + x][ViewPos.Y + y] ,this->_default };
            }
        }
    }
    this->_UIBuf->Update();
}

void CInputBox::UpdateData(bool isDown)
{
    if (isDown)this->_innerText = this->_bufText;
    else
    {
        this->_bufText = this->_innerText;
        this->_BufPos = { 0,0 };
        this->_CurPos = { 0,0 };
        this->uiupd();
    }
}
